package com.wemei.auto

import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.annotation.JSONField
import com.google.android.flexbox.FlexboxLayoutManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.BottomListPopupView
import com.wemei.auto.AppUpdateHelper.initUpdate
import com.wemei.auto.api.core.FirmException
import com.wemei.auto.api.core.ResultBean
import com.wemei.auto.api.core.launchUI
import com.wemei.auto.api.core.toData
import com.wemei.auto.cp_fast_accessibility.NodeWrapper
import com.wemei.auto.cp_fast_accessibility.isAccessibilityEnable
import com.wemei.auto.cp_fast_accessibility.requireAccessibility
import com.wemei.auto.databinding.ActivityMainBinding
import com.wemei.auto.ui.api.ApiObserver
import com.wemei.auto.ui.base.BaseActivity
import com.wemei.auto.ui.dialog.showAlertDialog
import com.wemei.auto.ui.ext.gone
import com.wemei.auto.ui.ext.toastMessageLong
import com.wemei.auto.ui.ext.value
import com.wemei.auto.ui.ext.visible
import com.wemei.auto.ui.helper.mohsi.MoshiUtils
import com.wemei.auto.ui.utils.Logger
import com.wemei.auto.ui.utils.SPUtils
import kotlinx.coroutines.delay
import me.jessyan.autosize.utils.ScreenUtils

val PSF = arrayOf(
    "广东", "广西", "海南", "湖南", "河北", "山西", "辽宁", "吉林", "黑龙江", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "四川",
    "贵州", "云南", "陕西", "甘肃", "青海", "台湾", "内蒙", "西藏", "宁夏", "新疆", "北京", "天津", "上海", "重庆", "香港", "澳门"
)

val XB = arrayOf("女", "男")

class MainActivity : BaseActivity<ActivityMainBinding>() {
    private lateinit var texts: MutableList<String>
    private lateinit var jetexts: MutableList<String>
    private lateinit var mTextAdapter: SimpleAdapter
    private lateinit var mJeTextAdapter: SimpleAdapter
    private var view: View? = null
    private lateinit var mXbPv: BottomListPopupView
    private lateinit var mSfPv: BottomListPopupView


    override fun initView() {
        bindViewClick(vb.etTag1, vb.etTag2, vb.buttonJj, vb.buttonAdd, vb.buttonLogin, vb.buttonLogout, vb.buttonStart)

        vb.tvSxCentent.setText(SPUtils.getString("sx_centent"))
        vb.tvMaxCentent.text = SPUtils.getString("sx_max_centent", "25")
        vb.etTag1.text = XB.find { it == SPUtils.getString("user_tag1") } ?: ""
        vb.etTag2.text = PSF.find { it == SPUtils.getString("user_tag2") } ?: ""
        SPUtils.put("user_tag1", vb.etTag1.value)
        SPUtils.put("user_tag2", vb.etTag2.value)
        vb.etTag1.doAfterTextChanged { SPUtils.put("user_tag1", it.toString()) }
        vb.etTag2.doAfterTextChanged { SPUtils.put("user_tag2", it.toString()) }
        vb.llPpf.isVisible = false
        vb.cbCurVideoDz.setOnClickListener { SPUtils.put("curVideoDz", vb.cbCurVideoDz.isChecked) }
        vb.cbCurVideoSx.setOnClickListener { SPUtils.put("curVideoSx", vb.cbCurVideoSx.isChecked) }

        vb.tvSxCentent.doAfterTextChanged { SPUtils.put("sx_centent", it.toString()) }
        vb.tvMaxCentent.doAfterTextChanged { SPUtils.put("sx_max_centent", it.toString()) }

        jetexts = JSON.parseArray(SPUtils.getString("jetexts", "[]"), String::class.java)
        Logger.e("本次运评价关键字：${JSON.toJSONString(jetexts)}")
        mJeTextAdapter = SimpleAdapter(jetexts)
        vb.rvJjText.adapter = mJeTextAdapter
        vb.rvJjText.layoutManager = FlexboxLayoutManager(this)

        texts = JSON.parseArray(SPUtils.getString("texts", "[]"), String::class.java)
        Logger.e("本次运简介关键字：${JSON.toJSONString(jetexts)}")
        mTextAdapter = SimpleAdapter(texts)
        vb.rvText.adapter = mTextAdapter
        vb.rvText.layoutManager = FlexboxLayoutManager(this)

        launchUI({
            userGet()
            loadGjc()
        })
        launchUI({
            while (true) {
                delay(1000 * 60)
                userGet()
                if (checkExpiration() && isAccessibilityEnable) {
                    MyAccessibilityService.instance?.end(false)
                }
            }
        })
        launchUI({
            while (true) {
                loadGjc()
                delay(1000 * 60 * 5)
            }
        }, ApiObserver(error = { "关键词获取失败，请重新杀掉程序重新启动或等待5分钟。".toastMessageLong() }))
        initUpdate()

        mXbPv = XPopup.Builder(mThis)
            .enableDrag(false)
            .maxHeight(ScreenUtils.getScreenSize(mThis)[1] / 2)
            .asBottomList("请选性别", XB) { position, text ->
                vb.etTag1.text = text
            }
        mSfPv = XPopup.Builder(mThis)
            .enableDrag(false)
            .maxHeight(ScreenUtils.getScreenSize(mThis)[1] / 2)
            .asBottomList("请选省份", PSF) { position, text ->
                vb.etTag2.text = text
            }
    }

    private suspend fun loadGjc() {
        runCatching {
            val userInfoStr = SPUtils.getString("userInfo")
            if (userInfoStr.isNotBlank()) {
                val mUserBean = MoshiUtils.parseObject(userInfoStr, UserBean::class.java)
                vb.llPpf.isVisible = mUserBean?.category == "lb_pingpaifang"
                if (vb.llPpf.isVisible) {
                    vb.cbCurVideoSx.isChecked = SPUtils.getBoolean("curVideoSx", false)
                    vb.cbCurVideoDz.isChecked = SPUtils.getBoolean("curVideoDz", false)
                } else {
                    SPUtils.remove("curVideoSx")
                    SPUtils.remove("curVideoDz")
                }

                val datas = API_SERVICE.getDictDataListByType(mUserBean?.industry).data
                datas?.find { it.label == "简介" }?.let {
                    val toList = it.remark.split("，").asSequence()
                        .filter(String::isNotBlank)
                        .filter { !jetexts.contains(it) }
                        .toList()
                    if (toList.isNotEmpty()) {
                        jetexts.addAll(toList)
                        mJeTextAdapter.notifyDataSetChanged()
                        SPUtils.put("jetexts", JSON.toJSONString(jetexts))
                    }
                }
                datas?.find { it.label == "评论" }?.let {
                    val toList = it.remark.split("，").asSequence()
                        .filter(String::isNotBlank)
                        .filter { !texts.contains(it) }
                        .toList()
                    if (toList.isNotEmpty()) {
                        texts.addAll(toList)
                        mTextAdapter.notifyDataSetChanged()
                        SPUtils.put("texts", JSON.toJSONString(texts))
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.etTag1 -> mXbPv.show()
            vb.etTag2 -> mSfPv.show()
            vb.buttonStart -> {
                if (vb.llUserinfo.isGone) {
                    "请先登录".toastMessageLong()
                    return
                }
                if (checkExpiration()) {
                    "使用已到期，请联系管理员。".toastMessageLong()
                    return
                }
                if (vb.tvMaxCentent.value.isEmpty()) {
                    "请先设置最大私信数。".toastMessageLong()
                    return
                }
                if (vb.tvSxCentent.value.isEmpty()) {
                    "请先设置私信内容。".toastMessageLong()
                    return
                }
                if (jetexts.isEmpty()) {
                    "请先新增简介关键字。".toastMessageLong()
                    return
                }
                if (texts.isEmpty()) {
                    "请先新增评论关键字。".toastMessageLong()
                    return
                }
                if (!Settings.canDrawOverlays(this)) {
                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                    startActivity(intent)
                    "请授悬浮窗权限".toastMessageLong()
                    return
                }
                val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                val isNotificationEnabled = notificationManager.areNotificationsEnabled()
                if (!isNotificationEnabled) {
                    val intent = Intent()
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                        intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
                        intent.putExtra("app_package", packageName)
                        intent.putExtra("app_uid", applicationInfo.uid)
                    } else {
                        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                        intent.addCategory(Intent.CATEGORY_DEFAULT)
                        intent.data = Uri.parse("package:$packageName")
                    }
                    startActivity(intent)
                    "请授权通知权限".toastMessageLong()
                    return
                }
                if (!isAccessibilityEnable) {
                    requireAccessibility()
                    "请开启无障碍服务".toastMessageLong()
                    return
                } else {
                    MyAccessibilityService.instance?.showFloatWindow()
                }
            }

            vb.buttonLogin -> {
                launchUI({
                    val body = JSONObject()
                    body["username"] = vb.etPhone.value
                    body["password"] = vb.etPassword.value
                    val mAccessTokenBean = api.authLogin(body).toData() ?: throw FirmException("登录失败")
                    SPUtils.put("accessToken", mAccessTokenBean.accessToken)
                    userGet()
                    loadGjc()
                }, ApiObserver(this))
            }

            vb.buttonLogout -> {
                showAlertDialog {
                    message("确定退出登录吗？")
                    negativeButton { }
                    positiveButton {
                        SPUtils.remove("accessToken")
                        SPUtils.remove("userInfo")
                        changeUserInfo()
                    }
                }
            }

            vb.buttonJj -> {
                view = vb.buttonJj
                showEditDialog()
            }

            vb.buttonAdd -> {
                view = vb.buttonAdd
                showEditDialog()
            }
        }
    }

    private suspend fun userGet() {
        val accessToken = SPUtils.getString("accessToken")
        if (accessToken.isNotBlank()) {
            val result = API_SERVICE.userGet(accessToken)
            if (result.code == ResultBean.NOT_LOGIN || result.data == null) {
                SPUtils.remove("accessToken")
                SPUtils.remove("userInfo")
            } else if (result.isOk) {
                SPUtils.put("userInfo", MoshiUtils.toJSONString(result.data!!))
            }
        }
        changeUserInfo()
    }

    private fun changeUserInfo() {
        val userInfoStr = SPUtils.getString("userInfo")
        if (userInfoStr.isBlank()) {
            vb.llLogin.visible()
            vb.llUserinfo.gone()
        } else {
            vb.llLogin.gone()
            vb.llUserinfo.visible()
            val mUserBean = MoshiUtils.parseObject(userInfoStr, UserBean::class.java)
            vb.tvEd.text = "到期时间：" + mUserBean?.expirationDate
        }
    }

    // 显示编辑对话框
    private fun showEditDialog() {
        // 创建自定义对话框视图
        val dialogView: View = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null)
        val editText = dialogView.findViewById<EditText>(R.id.editText)

        // 创建对话框
        val dialog: AlertDialog = AlertDialog.Builder(this)
            .setTitle("输入关键字")
            .setView(dialogView)
            .setPositiveButton("确认") { d, which ->
                val newText = editText.text.toString().trim { it <= ' ' }
                if (newText.isNotEmpty()) {
                    when (view) {
                        vb.buttonJj -> {
                            jetexts.add(newText)
                            mJeTextAdapter.notifyDataSetChanged()
                            SPUtils.put("jetexts", JSON.toJSONString(jetexts))
                        }

                        vb.buttonAdd -> {
                            texts.add(newText)
                            mTextAdapter.notifyDataSetChanged()
                            SPUtils.put("texts", JSON.toJSONString(texts))
                        }
                    }
                } else {
                    Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .create()

        dialog.show()
    }

    override fun onResume() {
        super.onResume()
        if (isAccessibilityEnable) {
            vb.tvServiceStatus.text = getStringRes(R.string.service_status_enable)
            MyAccessibilityService.instance?.showFloatWindow()
        } else {
            vb.tvServiceStatus.text = getStringRes(R.string.service_status_disable)
        }
        if (Settings.canDrawOverlays(this)) {
            vb.tvXfc.text = "1、悬浮窗已授权"
        } else {
            vb.tvXfc.text = "1、悬浮窗未授权"
        }
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val isNotificationEnabled = notificationManager.areNotificationsEnabled()
        if (isNotificationEnabled) {
            vb.tvTz.text = "2、通知已授权"
        } else {
            vb.tvTz.text = "2、通知未授权"
        }
    }

    class Item {
        var text: String = ""
    }

    inner class SimpleAdapter(
        private val items: MutableList<String>,
    ) : RecyclerView.Adapter<SimpleAdapter.ViewHolder>() {

        // 创建 ViewHolder
        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val textView: TextView = view.findViewById(R.id.tvText)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.textView.text = items[position]
            holder.textView.setOnLongClickListener {
                AlertDialog.Builder(holder.textView.context)
                    .setTitle("确认操作")
                    .setMessage("您确定要删除吗？")
                    .setPositiveButton("确定") { dialog, which ->
                        items.removeAt(position)
                        notifyDataSetChanged()
                        Toast.makeText(holder.textView.context, "已删除", Toast.LENGTH_SHORT).show()
                        SPUtils.edit(true) {
                            putString("texts", JSON.toJSONString(texts))
                        }
                    }
                    .setNegativeButton("取消", null)
                    .show()
                true
            }
        }

        override fun getItemCount() = items.size
    }
}

class DyUser {
    @JSONField(serialize = false, deserialize = false)
    var avatarNode: NodeWrapper? = null
    var avatar: String? = null
    var title: String? = null
    var content: String? = null
}
